import tkinter as tk
import pyttsx3
import time
import random
import re
import random
import threading
from tkinter import messagebox
SLEEPSECONDS = 5 #单词间隔,秒
REPEAT = 3 #每词重复次数
WordList = [] #待听写的词列表
Status = 0 #播放状态，0表示停止，1表示播放中
ResultList = []
Pause = False #暂停碰碎
def check_pause():#wait if pause is set
    while True:
        if not Pause:
            break
def text_to_speech(text,sp):
    global Status,ResultList
    # 初始化 pyttsx3 引擎
    engine = pyttsx3.init()
    # vs = engine.getProperty('voices')
    # print(vs)

    # 设置语速（可选）
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate - 50)
    engine.setProperty('voice', 'Huihui')

    words = text
    i = 1
    result = []
    for word in words:
        tts = f'第{i}个：{word}'
        result.append(tts)
        for _ in range(REPEAT):  # 每个词读三遍
            if Status:
                check_pause()
                engine.say(tts)
                engine.runAndWait()
                for _ in range(SLEEPSECONDS*4):
                    if Status:
                        time.sleep(0.25)  # 每遍之间间隔 3 秒
                    else:
                        Status = 1
                        return None
            else:
                Status = 1 #提前退出
                return None
        i = i + 1
    Status = 0 #播放完成
    engine.say("太棒了,听写完成")
    engine.runAndWait()
    sp()
    # ResultList = result
    return 1
def is_all_chinese(s):
    for char in s:
        if not '\u4e00' <= char <= '\u9fff':
            return False
    return True
# # 示例
# print(is_all_chinese("你好世界"))  # 输出: True
# print(is_all_chinese("Hello, World"))  # 输出: False
# print(is_all_chinese("你好，World"))  # 输出: False
def replace_chinese_brackets(s):
    # 替换全角左括号（为英文左括号(
    s = s.replace('（', '(')
    # 替换全角右括号）为英文右括号)
    s = s.replace('）', ')')
    return s
# # 示例
# s = "这是一个（示例）字符串"
# new_s = replace_chinese_brackets(s)
# print(new_s)  # 输出: 这是一个(示例)字符串
def extract_first_char_and_brackets(s):
    # 去除字符串前后的空格
    s = s.strip()
    # 匹配第一个字符和括号内的内容
    pattern = r'^(.)(\(.*?\))+'
    # 搜索匹配项
    match = re.search(pattern, s)
    if match:
        # 提取第一个字符
        first_char = match.group(1)
        # 提取括号内的内容（以列表形式返回）
        brackets = re.findall(r'\(.*?\)', s)
        # 如果需要去掉括号，可以进一步处理
        brackets_without_parens = [x[1:-1].strip() for x in brackets]
        random.shuffle( brackets_without_parens)
        return first_char+"。"+brackets_without_parens[0]
    else:
        return None  # 如果没有匹配项，返回None
# 示例
# s = "   丝(雨丝)( 丝瓜)(丝带)   "
# s = "   丝(雨丝( 丝瓜(丝带   "
# brackets = extract_first_char_and_brackets(s)
# print(f"括号中的字符串: {brackets}")

def get_word_list(wl):
    result = []
    lines = wl.strip().split("\n")
    for line in lines:
        ex = extract_first_char_and_brackets(line)
        if ex:
            result.append(ex)
        else:
            result.append(line)
    return result
# 假设我们有一个包含多行的字符串
# multi_line_string = """
# 冲(冲动)(冲破)(冲出)
# 寻(寻找)(寻人)(寻求)
# 姑(姑娘)(姑姑)(姑妈)
# 娘(新娘)(大娘)(娘家)
# 吐(吞吐)(吐丝)(扬眉吐气)
# 柳(柳枝)(柳树)(杨柳)
# 荡(回荡)(飘荡)(荡秋千)
# 桃(桃花)(桃李)(桃树)
# 杏(杏花)(杏子)(杏树)
# 仔(仔细)(仔鸡)(牛仔)
# 春天
# 野花
# 秋千
# """
# print(get_word_list(multi_line_string))
if __name__ == "__main__":
    # 创建主窗口，并设置窗口大小
    root = tk.Tk()
    root.geometry("1000x650")  # 可根据需要调整大小
    up_frame = tk.Frame(root, width=300, height=100, bd=2 )
    up_frame.pack()
    bt_frame = tk.Frame(up_frame, width=300, height=100, bd=2)
    bt_frame.pack()
    down_frame = tk.Frame(root, width=300, height=500, bd=2)
    down_frame.pack()
    conf_frame = tk.Frame(root, width=300, height=100, bd=2)
    conf_frame.pack()
    label_repeat = tk.Label(conf_frame, text="每词重复次数:",font=("宋体", 12))
    label_repeat.grid(row=0,column=0,sticky='w')
    entry_repeat = tk.Entry(conf_frame)
    entry_repeat.insert(0, f'{REPEAT}')
    entry_repeat.grid(row=0,column=1,sticky='w')
    # 绑定回车键事件
    def on_repeat_change(event):
        global REPEAT
        # 获取Entry中的文本内容
        input_text = event.widget.get()
        try:
            # 尝试将字符串转换为整数
            REPEAT = int(input_text)
        except ValueError:
            messagebox.showwarning("Warning", "请输入整数！")
    entry_repeat.bind('<Return>', on_repeat_change)
    # 绑定焦点离开事件
    entry_repeat.bind('<FocusOut>', on_repeat_change)
    label_dummy = tk.Label(conf_frame, text="    ",font=("宋体", 12))
    label_dummy.grid(row=0,column=2,sticky='w')
    label_sleep = tk.Label(conf_frame, text="间隔时间（秒）:",font=("宋体", 12))
    label_sleep.grid(row=0,column=3,sticky='w')
    entry_sleep = tk.Entry(conf_frame)
    entry_sleep.grid(row=0,column=4,sticky='w')
    entry_sleep.insert(0, f'{SLEEPSECONDS}')
    def on_sleep_change(event):
        global SLEEPSECONDS
        # 获取Entry中的文本内容
        input_text = event.widget.get()
        try:
            # 尝试将字符串转换为整数
            SLEEPSECONDS = int(input_text)
        except ValueError:
            messagebox.showwarning("Warning", "请输入整数！")
            event.widget.focus_set()
    # 创建输入框上面的文本标签，内容为：待听写内容
    entry_sleep.bind('<Return>', on_sleep_change)
    entry_sleep.bind('<FocusOut>', on_sleep_change)
    label_title = tk.Label(down_frame, text="待听写内容:",font=("宋体", 12))
    # label_title.pack(side=tk.TOP)
    label_title.grid(row=1,column=0,sticky='w')
    label_title2 = tk.Label(down_frame, text="听写结果:",font=("宋体", 12))
    # label_title.pack(side=tk.TOP)
    label_title2.grid(row=1,column=1,sticky='w')

    # 创建输入框
    textbox = tk.Text(down_frame, wrap=tk.WORD, height=25,width=40,font=("宋体", 16))  # 设置为多行文本框，并允许自动换行
    # textbox.pack(side=tk.LEFT)
    textbox.grid(row=2,column=0)

    # 创建输入框下面的文本标签，用于显示 text_to_speech 函数的返回结果
    textbox2= tk.Text(down_frame, wrap=tk.WORD, height=25,width=40,font=("宋体", 16))  # 设置为多行文本框，并允许自动换行
    # textbox2.pack(side=tk.RIGHT)
    textbox2.grid(row=2,column=1)
    # 按钮用于触发文本转语音功能
    button = tk.Button(bt_frame, text="开始听写", command=lambda: process_entry(textbox.get("1.0", tk.END)),font=("宋体", 12))
    # button.pack()
    button.pack(side=tk.LEFT)
    button_stop = tk.Button(bt_frame, text="停止", command=lambda: stop_playing(),font=("宋体", 12))
    button_stop.pack(side=tk.RIGHT)
    button_resume = tk.Button(bt_frame, text="继续", command=lambda: resume_playing(),font=("宋体", 12))
    button_resume.pack(side=tk.RIGHT)
    button_pause = tk.Button(bt_frame, text="暂停", command=lambda: pause_playing(),font=("宋体", 12))
    button_pause.pack(side=tk.RIGHT)
    button_resume.config(state='disabled')
    button_pause.config(state='disabled')
    button_stop.config(state='disabled')

# 在这里可以添加其他处理逻辑
    def pause_playing():
        global Pause
        if Pause:
            Pause = False
        else:
            Pause = True
        button_pause.config(state='disabled')
        button_resume.config(state='normal')
    def resume_playing():
        global Pause
        if Pause:
            Pause = False
        else:
            Pause = True
        button_pause.config(state='normal')
        button_resume.config(state='disabled')
    def stop_playing():
        global Status
        Status = 0
        while True:
            if Status:
                Status = 0
                break
        button_resume.config(state='disabled')
        button_pause.config(state='disabled')
        button_stop.config(state='disabled')
        button.config(state='normal')
    def end_playing():
        global Status
        Status = 0
        button_resume.config(state='disabled')
        button_pause.config(state='disabled')
        button_stop.config(state='disabled')
        button.config(state='normal')
    def set_text(tb,text):
        tb.delete("1.0", tk.END)
        tb.insert("1.0",text)
    def process_entry(text):
        global  Status
        Status = 1
        button.config(state='disabled')
        button_resume.config(state='disabled')
        button_pause.config(state='normal')
        button_stop.config(state='normal')
        # set_text(textbox2,"正在听写中……")
        root.update()
        # result = text_to_speech(text)
        # set_text(textbox2,"听写结束！\n"+"\n".join(result))
        WordList = get_word_list(text)
        random.shuffle(WordList )
        # 创建一个Thread对象，将目标函数作为参数
        thread = threading.Thread(target=text_to_speech, args=(WordList,end_playing,))
        i = 1
        dispResult = []
        for word in WordList:
           dispResult.append(f'{i}. {word.replace("。","，")}')
           i = i+1
        set_text(textbox2,"\n".join(dispResult))

        # 启动线程
        thread.start()
# 主事件循环
    root.mainloop()